package com.advertisementsystem.utils;

import com.advertisementsystem.Exception.BusinessException;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import java.util.Map;
@Slf4j
public class PayUtils {
    @Value("${payment.alipay.publicKey}")
    private static String alipayPublicKey;

    @Value("${payment.wechat.apiKey}")
    private static String wechatApiKey;

    /**
     * 验证支付回调签名
     */
    public static boolean verifySign(String payMethod, HttpServletRequest request) {
        try {
            if ("ALIPAY".equals(payMethod)) {
                return verifyAlipaySign(request);
            } else if ("WECHAT".equals(payMethod)) {
                return verifyWechatSign(request);
            }
            return false;
        } catch (Exception e) {
            log.error("Verify sign error", e);
            return false;
        }
    }

    /**
     * 验证支付宝回调签名
     */
    private static boolean verifyAlipaySign(HttpServletRequest request) throws AlipayApiException, AlipayApiException {
        // 获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        // 调用SDK验证签名
        return AlipaySignature.rsaCheckV1(params, alipayPublicKey, "UTF-8", "RSA2");
    }

    /**
     * 验证微信支付回调签名
     */
    private static boolean verifyWechatSign(HttpServletRequest request) throws Exception {
        String xmlData = readXmlFromRequest(request);
        Map<String, String> params = WXPayUtil.xmlToMap(xmlData);

        // 验证签名
        return WXPayUtil.isSignatureValid(params, wechatApiKey);
    }

    /**
     * 获取订单号
     */
    public static String getOrderNo(String payMethod, HttpServletRequest request) {
        if ("ALIPAY".equals(payMethod)) {
            // 支付宝的商户订单号
            return request.getParameter("out_trade_no");
        } else if ("WECHAT".equals(payMethod)) {
            try {
                String xmlData = readXmlFromRequest(request);
                Map<String, String> params = WXPayUtil.xmlToMap(xmlData);
                return params.get("out_trade_no");
            } catch (Exception e) {
                log.error("Get wechat order no error", e);
                throw new BusinessException("解析微信支付回调参数失败");
            }
        }
        throw new BusinessException("不支持的支付方式");
    }

    /**
     * 获取交易号
     */
    public static String getTransactionId(String payMethod, HttpServletRequest request) {
        if ("ALIPAY".equals(payMethod)) {
            // 支付宝交易号
            return request.getParameter("trade_no");
        } else if ("WECHAT".equals(payMethod)) {
            try {
                String xmlData = readXmlFromRequest(request);
                Map<String, String> params = WXPayUtil.xmlToMap(xmlData);
                return params.get("transaction_id");
            } catch (Exception e) {
                log.error("Get wechat transaction id error", e);
                throw new BusinessException("解析微信支付回调参数失败");
            }
        }
        throw new BusinessException("不支持的支付方式");
    }

    /**
     * 获取支付状态
     */
    public static Integer getPayStatus(String payMethod, HttpServletRequest request) {
        if ("ALIPAY".equals(payMethod)) {
            // 支付宝交易状态
            String tradeStatus = request.getParameter("trade_status");
            switch (tradeStatus) {
                case "TRADE_SUCCESS":
                case "TRADE_FINISHED":
                    return 1; // 支付成功
                case "TRADE_CLOSED":
                    return 2; // 支付失败
                default:
                    return 0; // 其他状态
            }
        } else if ("WECHAT".equals(payMethod)) {
            try {
                String xmlData = readXmlFromRequest(request);
                Map<String, String> params = WXPayUtil.xmlToMap(xmlData);
                String resultCode = params.get("result_code");
                if ("SUCCESS".equals(resultCode)) {
                    return 1; // 支付成功
                } else {
                    return 2; // 支付失败
                }
            } catch (Exception e) {
                log.error("Get wechat pay status error", e);
                throw new BusinessException("解析微信支付回调参数失败");
            }
        }
        throw new BusinessException("不支持的支付方式");
    }

    /**
     * 从请求中读取XML数据
     */
    private static String readXmlFromRequest(HttpServletRequest request) throws IOException {
        try (BufferedReader reader = request.getReader()) {
            StringBuilder xml = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                xml.append(line);
            }
            return xml.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

















}
